package com.sh.service.impl;

import com.sh.mapper.BoatMapper;
import com.sh.pojo.Boat;
import com.sh.service.BoadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class BoadServiceImpl implements BoadService {
    @Autowired
    public BoatMapper boatMapper;

//    @Override
//    public String getmeassage() {
//        try {
//            DatagramSocket socket = new DatagramSocket(8888); // 绑定接收端口
//            byte[] buffer = new byte[1024];
//            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//            socket.receive(packet); // 阻塞等待数据
//            // 解析数据（处理中文编码）
//            String receivedData = new String(
//                    packet.getData(), 0, packet.getLength(), "UTF-8"
//            );
//            InetAddress sourceIP = packet.getAddress();
//            int sourcePort = packet.getPort();
//
//            System.out.println("来自 " + sourceIP + "端口号：" + sourcePort + " 的数据: " + receivedData);
//            Boat boat = new Boat();
//            boat.setIp(sourceIP.toString());
//            boat.setPort(sourcePort);
//            boat.setMessage(receivedData);
//            boatMapper.update(boat);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

//    @Override
//    public void sendmeassage(String message) {
//        //获取ip加端口号
//        Boat boat = boatMapper.getBoat();
//        String ip = boat.getIp();
//        int port = boat.getPort();
//        // 创建一个 UDP 套接字
//        try (DatagramSocket socket = new DatagramSocket()) {
//            while (true) {
//
//                byte[] data = message.getBytes();
//                // 创建数据包，包含数据、目标 IP 地址和端口号
//                DatagramPacket packet = new DatagramPacket(
//                        data,
//                        data.length,
//                        InetAddress.getByName(ip),
//                        port
//                );
//                socket.send(packet);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
   private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    private DatagramSocket socket = new DatagramSocket(); // 单例 Socket

    public BoadServiceImpl() throws SocketException {
    }

    public void sendmeassage(String message) {
        executor.schedule(() -> {
            log.info("发送数据：" + message);
            Boat boat = boatMapper.getBoat();
            byte[] data = message.getBytes(StandardCharsets.UTF_8); // ✅ 指定编码

            DatagramPacket packet = null;
            try {
                packet = new DatagramPacket(
                        data,
                        data.length,
                        InetAddress.getByName(boat.getIp()),
                        boat.getPort()
                );
            } catch (UnknownHostException e) {
                throw new RuntimeException(e);
            }

            try {
                log.info("发送数据：" + message);
                socket.send(packet); // ✅ 复用 Socket
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 0, TimeUnit.MILLISECONDS); // 立即发送但不阻塞
    }

    @PreDestroy
    public void shutdown() {
        executor.shutdown();    // 关闭线程池
        socket.close();         // 关闭 Socket
    }
}
